﻿using System.Data;
using System.Data.Objects;
using System.Linq;

namespace YawetagLib.Data.L2EF
{
    public sealed class ObjectContextAdapter : IQueryableDataContext
    {
        public ObjectContextAdapter(ObjectContext current)
        {
            Current = current;
        }

        public void OpenConnection()
        {
            Connection.Open();
        }

        public void CloseConnection()
        {
            Connection.Close();
        }

        public IDataSource<TEntity> GetDataSource<TEntity>() where TEntity : class
        {
            return new ObjectContextDataSource<TEntity>(GetDataSet<TEntity>());
        }

        public void SubmitChanges()
        {
            Current.SaveChanges();
        }

        public IQueryable<TEntity> GetDataSet<TEntity>() where TEntity : class
        {
            return Current.CreateObjectSet<TEntity>();
        }

        public void Dispose()
        {
            Current.Dispose();
        }

        object IDataContext.Current
        {
            get { return Current; }
        }

        private ObjectContext Current { get; set; }

        private IDbConnection Connection
        {
            get { return Current.Connection; }
        }
    }
}
